package com.wsn.mongodb.mongodbdemo.service;

import cn.hutool.core.util.StrUtil;
import com.wsn.mongodb.mongodbdemo.entity.User;
import com.wsn.mongodb.mongodbdemo.template.MongoTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description: 测试接口
 * @ClassName: TestServiceImpl
 * @Author: weisn
 * @Date: 2022/5/20 16:45
 * @Version: 1.0
 */
@Service(value = "testService")
public class TestServiceImpl implements TestService {
    @Autowired
    private MongoTemplateUtil mongoTemplate;

    /**
     * 新增用户
     * @author weisn 
     * @param user:
     * @see User
     * @date 2022/5/20 17:21
     */
    @Override
    public Object addUser(Object user) {
        return mongoTemplate.insert(user,"user_info");
    }

    /**
     * 删除用户
     * @author weisn 
     * @param user:
     * @see Long
     * @date 2022/5/20 17:23
     */
    @Override
    public Long delUser(User user) {
        Query query = Query.query(Criteria.where("name").is(user.getName()).and("id").is(user.getId()));
        return mongoTemplate.remove(query,User.class,"user_info");
    }

    /**
     * 获取用户列表
     *
     * @param user : 用户信息
     * @author weisn
     * @date 2022/5/20 16:58
     * @see List < User>
     */
    @Override
    public List<User> getUserList(User user) {
        Criteria criteria = Criteria.where("");
        if (StrUtil.isNotBlank(user.getName())) {
            criteria.and("name").is(user.getName());
        }
        return mongoTemplate.find(new Query(criteria),User.class,"user_info");
    }

    /**
     * 通过用户id获取用户信息
     *
     * @param userId :
     * @author weisn
     * @date 2022/5/20 17:13
     * @see User
     */
    @Override
    public User getUserById(Integer userId) {
        return mongoTemplate.findById(userId,User.class);
    }
}
